//
//  TopicFocusViewController.swift
//  HoneyBee
//
//  Created by point on 2018/1/24.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import MJRefresh

private let kCellID = "kMyTopicCellId"

class TopicFocusViewController: UIViewController {

    @IBOutlet weak var noFocusView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var focusIcon: UIImageView!
    @IBOutlet weak var focusLabel: UILabel!
    
    fileprivate lazy var topicModelList: [TopicModel] = [TopicModel]()
    
    var pageNo : Int = 1
    var pageSize: Int = 10

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    public func loadData(){
        
        self.hudLoad()
        
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "pageNo":self.pageNo,
            "pageSize":self.pageSize] as [String : Any]
        
        TempNetTool.post( kHost + kqueryMyGroupTopicList + "".apiF(time: "1", sign: "dd") + "&pageNo=\(self.pageNo)" + "&pageSize=\(self.pageSize)", parameters: dict, progress: nil, success: { [weak self] (result) in
            
            self?.hudHide()

            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            if (self?.pageNo == 1) {
                self?.topicModelList.removeAll()
            }
            if (result != nil) {
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [NSObject] else { return }
                let topicModels = TopicModel.tmSpeelBreakModelArr(dataArray)
                
                if (topicModels.count < (self?.pageSize)!){
                    self?.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                self?.topicModelList.append(contentsOf: (topicModels as? [TopicModel])!)
                self?.tableView.reloadData()
                
                if ((self?.topicModelList.count)! > 0){
                    self?.noFocusView.isHidden = true;
                } else {
                    self?.noFocusView.isHidden = false;
                }

                
            }
            
            
        }) {[weak self]   (error) in
            self?.hudHide()
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            
        }
        
    }
    
}


extension TopicFocusViewController:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.topicModelList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kCellID, for: indexPath) as! TopicTableViewCell
        cell.configModel(model: self.topicModelList[indexPath.item], index: indexPath)
        cell.deleteBlock = {
            let deleteConfirmVC =  TopicDeleteViewController()
            self.navigationController?.pushViewController(deleteConfirmVC, animated: true)
            deleteConfirmVC.topicModel = (self.topicModelList[indexPath.row]);
            deleteConfirmVC.deletedBlock = {(isSuccess) in
                if (isSuccess){
                    self.topicModelList.remove(at: indexPath.row )
                    self.tableView.reloadData()
                }
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: false)
        
        let model = self.topicModelList[indexPath.item]
        let vc = TopicDetailViewController()
        vc.configModel(model: model);
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    
}


extension TopicFocusViewController {
    fileprivate func setupUI(){
        
        noFocusView.layer.cornerRadius = 3
        noFocusView.layer.backgroundColor = UIColor(red: 255.0 / 255.0, green: 255.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0).cgColor
        noFocusView.alpha = 1
        
        //Shadow 0 for 圆角矩形 5
        let shadowLayer0 = CALayer()
        shadowLayer0.frame = noFocusView.bounds
        shadowLayer0.shadowColor = UIColor(red: 121.0 / 255.0, green: 121.0 / 255.0, blue: 121.0 / 255.0, alpha: 0.04).cgColor
        shadowLayer0.shadowOpacity = 1
        shadowLayer0.shadowOffset = CGSize(width: 0, height: 2)
        shadowLayer0.shadowRadius = 2
        let shadowSize0:CGFloat = 1
        let shadowSpreadRect0 = CGRect(x: -shadowSize0, y: -shadowSize0, width: noFocusView.bounds.size.width+shadowSize0*2, height: noFocusView.bounds.size.height+shadowSize0*2)
        let shadowSpreadRadius0 =  noFocusView.layer.cornerRadius == 0 ? 0 : noFocusView.layer.cornerRadius+shadowSize0;
        let shadowPath0 = UIBezierPath(roundedRect: shadowSpreadRect0, cornerRadius: shadowSpreadRadius0)
        shadowLayer0.shadowPath = shadowPath0.cgPath;
        noFocusView.layer.addSublayer(shadowLayer0)
        
        let attributedString = NSMutableAttributedString(string: "暂无关注的话题，快去关注吧~~！")
        attributedString.addAttributes([NSAttributedString.Key.font : UIFont(name: "PingFang-SC-Medium", size: 12.0)!, NSAttributedString.Key.foregroundColor:UIColor(red: 153.0 / 255.0, green: 153.0 / 255.0, blue: 153.0 / 255.0, alpha: 1.0)], range: NSRange(location: 0, length: attributedString.string.count))
        focusLabel.attributedText = attributedString;
        
        tableView.register(UINib(nibName: "TopicTableViewCell", bundle: nil), forCellReuseIdentifier: kCellID)
        tableView.separatorStyle = .singleLine
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView(frame: CGRect.zero);

        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.pageNo = 1
            self.loadData()
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            
            self.pageNo += 1
            self.loadData()
        })
        tableView.mj_header.beginRefreshing()
        
    }
    
}
